<template>
  <view class="home flex flex-col" :style="{ paddingTop: `${totalNavigationHeight * 2}rpx` }">
    <view class="home-top flex items-center">
      <button v-if="!loginFlag" open-type="getPhoneNumber" class="home-top-img" @getphonenumber="getPhoneNumber">
        <image class="button-img" :src="userStore.avatar || 'https://aireader-1302868088.cos.ap-nanjing.myqcloud.com/mini_icon/user_img.png'" />
      </button>
      <image v-else class="home-top-img" :src="userStore.avatar || 'https://aireader-1302868088.cos.ap-nanjing.myqcloud.com/mini_icon/user_img.png'" @click="userDetailShow = true" />
      <TabBar v-model="currentTab" :list="tabList" @change="onTabChange" />
    </view>
    <view class="home-content flex-1">
      <view class="content-icon" :style="{ left: `${scrollLeft}rpx` }" />
      <swiper
        class="swiper" :indicator-dots="false" :autoplay="false" :current="currentIndex"
        next-margin="32rpx" previous-margin="8rpx" @change="onSwiperChange"
      >
        <swiper-item v-for="(unit, unitIndex) in currentStage?.unit" :key="unit.id">
          <view class="swiper-item">
            <view class="item-top">
              <text class="item-top-text">
                共享成员：
              </text>
              <view class="item-top-images" @click="showUserList(currentStage)">
                <template v-for="(item, index) in currentStage?.memberList">
                  <image
                    v-if="index < 4"
                    :key="item.memberId"
                    class="item-top-img"
                    :src="item.memberAvatar"
                  />
                </template>
                <template v-if="(currentStage?.memberList?.length ?? 0) < 4">
                  <view v-for="item in 4 - (currentStage?.memberList?.length ?? 0)" :key="item" class="item-top-img" />
                </template>
              </view>
              <text class="item-top-text">
                {{ currentStage?.memberList?.length || 0 }}人
              </text>
            </view>

            <view class="item-content" :class="[`content-${unitIndex + 1}`]">
              <view class="item-stage">
                <view class="item-title flex">
                  <view class="item-title-index">
                    <text class="index-num">
                      {{ (unitIndex + 1).toString().padStart(2, '0') }}
                    </text>
                    <image class="index-img" src="https://aireader-1302868088.cos.ap-nanjing.myqcloud.com/mini_icon/icon_1.png" />
                  </view>
                  <text class="item-content-text">
                    {{ unit.name }}
                  </text>
                </view>
                <view v-if="unit.picture" class="item-image" @click="imagePreviewShow = true">
                  <image class="item-image-img" src="https://aireader-1302868088.cos.ap-nanjing.myqcloud.com/course_icons/zs_duan.png" mode="aspectFill" />
                  <view class="item-image-label">
                    课程体系
                  </view>
                </view>
                <view v-else class="item-desc">
                  {{ unit.description }}
                </view>
                <text v-if="unit.course?.length" class="item-subtitle">
                  {{ unit.trial ? '试听课' : '课程' }}
                </text>
                <view class="content-scroller">
                  <view v-for="(course, courseIndex) in unit.course" :key="`course-${course.id}`" class="item-course" @click="toCourseDetail(course)">
                    <view class="course-title">
                      <view class="course-title-label" :class="[`course-title-label-${(courseIndex + 1) % 2}`]">
                        <text class="label-text">
                          {{ course.subjectName }}
                        </text>
                      </view>
                      <text class="course-title-text">
                        {{ course.name }}
                      </text>
                    </view>
                    <text class="course-info">
                      {{ course.description }}
                    </text>
                    <button v-if="!loginFlag" class="course-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
                      <view class="btn-left">
                        <view class="btn-item" @click="handleCopy(1, course)">
                          拷贝报告
                        </view>
                        <view class="btn-item" @click="handleCopy(2, course)">
                          拷贝反馈
                        </view>
                      </view>
                      <view class="btn-right">
                        <up-icon name="arrow-right" color="#fff" :size="14" />
                      </view>
                    </button>
                    <view v-else class="course-btn">
                      <view class="btn-left">
                        <view class="btn-item" @click.stop="handleCopy(1, course)">
                          拷贝报告
                        </view>
                        <view class="btn-item" @click.stop="handleCopy(2, course)">
                          拷贝反馈
                        </view>
                      </view>
                      <view class="btn-right">
                        <up-icon name="arrow-right" color="#fff" :size="14" />
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    </view>

    <userDetail v-model:show="userDetailShow" @update-data="getData" />
    <inviteBox v-model:show="inviteShow" :share-data="shareData" @update-number="updateList" />
    <userList v-model:show="userListShow" :user-list="userListData" :stage="tabList[currentTab]" @update-list="updateList()" />
    <vipBox v-model:show="vipShow" @update-data="getData" />
    <imagePreview v-model:show="imagePreviewShow" @handle-click="handleClick" />
  </view>
</template>

<script setup lang="ts">
import userDetail from './components/userDetail.vue';
import inviteBox from './components/inviteBox.vue';
import userList from './components/userList.vue';
import vipBox from './components/vipBox.vue';
import imagePreview from './components/imagePreview.vue';
import storage from '@/utils/storage';
import TabBar from '@/components/tab-bar/index.vue';
import { useClipboard } from '@/hooks';
import { useCourseStore, useUserStore } from '@/store';
import { getCourse, getStage, getUnit } from '@/api/course';
import type { CourseData, StageList } from '@/api/course/types';
import { getLoginRecord, isLogin, setLoginRecord } from '@/utils/auth';
import { getMembers } from '@/api/user';
import type { MemberInfo } from '@/api/user/types';

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
});

const userStore = useUserStore();
const courseStore = useCourseStore();
const { setClipboardData } = useClipboard();

const loginFlag = ref<boolean>(isLogin()); // 是否登录

const totalNavigationHeight = ref<number>(0); // 导航栏总高度
const statusBarHeight = ref<number>(40); // 状态栏的高度
const navigatorHeight = ref<number>(40); // 导航栏高度
// 邀请
const inviteShow = ref(false);
const shareData = ref({});
const imagePreviewShow = ref(false); // 是否显示落地页 1-首次进入 2-点击招生素材图片
const isInvite = ref(false);
const handleClick = () => {
  if (isInvite.value)
    inviteShow.value = true;
};
onLoad((options: any) => {
  if (!getLoginRecord()) { // 首次进入
    imagePreviewShow.value = true;
    setLoginRecord();
  }

  if (options?.userId) { // 邀请进入
    isInvite.value = true;
    shareData.value = options;
    if (!imagePreviewShow.value)
      inviteShow.value = true;
  }
  else {
    isInvite.value = false;
  }

  uni.getSystemInfo({
    success: (res: any) => {
      statusBarHeight.value = res.statusBarHeight || 40;
    },
  });

  const menu: any = uni.getMenuButtonBoundingClientRect();
  // 导航栏高度= （胶囊顶部距离-状态栏高度） x 2 + 胶囊的高度
  const navigatorH = (menu.top - statusBarHeight.value) * 2 + menu.height;
  navigatorHeight.value = navigatorH <= 30 ? 40 : navigatorH;

  // 总高度 = 状态栏的高度 + 导航栏高度
  totalNavigationHeight.value = navigatorHeight.value + statusBarHeight.value;
  storage.set('navigation-total-height', totalNavigationHeight.value.toString());
});

const currentTab = ref(0); // 当前tab索引
const currentIndex = ref(0); // 当前单元索引
const tabList = ref<StageList[]>([]);
const currentStage = ref<StageList>();
const onTabChange = () => {
  currentStage.value = tabList.value[currentTab.value];
  currentIndex.value = 0;
};

// 获取当前阶段用户列表
const updateList = (satge?: StageList) => {
  getMembers({ stageId: satge?.id || tabList.value[currentTab.value].id }).then((res: MemberInfo[]) => {
    if (satge) {
      satge.memberList = res;
    }
    else {
      tabList.value[currentTab.value].memberList = res;
    }
  });
};
const getData = async () => {
  const stageRes = await getStage();
  for (let i = 0; i < stageRes.list.length; i++) {
    const stage = stageRes.list[i];
    // 获取该阶段成员列表
    if (loginFlag.value)
      updateList(stage);
    const unitRes = await getUnit({ stageId: stage.id });
    stage.unit = unitRes.list;
    for (let j = 0; j < stage.unit.length; j++) {
      const unit = stage.unit[j];
      const courseRes = await getCourse({ unitId: unit.id });
      unit.course = courseRes.list;
    }
  }
  tabList.value = stageRes.list;
  currentStage.value = tabList.value[currentTab.value];
};

onShow(async () => {
  if (loginFlag.value) {
    await userStore.info();
  }
  getData();
});

const onSwiperChange = (e: any) => {
  currentIndex.value = e.detail.current;
};

const scrollLeft = computed(() => {
  // 59 74 74 74 56
  if (currentTab.value <= 2) {
    return (59 + 74 * currentTab.value + 37) * 2 - 28;
  }
  return (59 + 74 * 3 + 28) * 2 - 28;
});

const vipShow = ref(false);
// 跳转到课程详情
const toCourseDetail = (course: CourseData) => {
  if (!loginFlag.value)
    return;
  if (!course.trial && !userStore.level) { // 会员课程 未购买
    vipShow.value = true;
    return;
  }
  uni.navigateTo({
    url: `/pages/views/course/detail?id=${course.id}`,
  });
};

// 用户详情
const userDetailShow = ref(false);

// 成员列表
const userListShow = ref(false);
const userListData = ref<MemberInfo[]>([]);

const showUserList = (stage: StageList | undefined) => {
  userListShow.value = true;
  userListData.value = stage?.memberList || [];
};

const handleCopy = async (type: number, course: CourseData) => {
  if (!course.trial && !userStore.level) { // 会员课程 未购买
    vipShow.value = true;
    return;
  }

  try {
    await courseStore.getCourseDetail(course.id);
    await setClipboardData({
      data: type === 1 ? courseStore.coursePreviewCopy : courseStore.contentDiffuseDetailCopy,
      showToast: true,
    });
  }
  catch (error) {
    console.error('复制失败:', error);
  }
};

// 获取手机号登录
const getPhoneNumber = (e: any) => { // 在bindgetphonenumber回调中获取code动态令牌
  userStore.mobileLogin(e.detail).then((res) => {
    if (res) {
      loginFlag.value = true;
      getData();
    }
  });
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;

  .home-top {
    .home-top-img {
      width: 66rpx;
      height: 66rpx;
      margin: 0 20rpx 0 32rpx;
      border-radius: 50%;

      .button-img {
        width: 66rpx;
        height: 66rpx;
      }
    }
  }

  .home-content {
    position: relative;
    width: 100%;
    flex: 1;
    margin-top: 52rpx;
    padding-top: 24rpx;
    background: #fff;
    border-radius: 48rpx 48rpx 0 0;

    .content-icon {
      position: absolute;
      top: -20rpx;
      width: 0;
      height: 0;
      border-left: 28rpx solid transparent;
      border-right: 28rpx solid transparent;
      border-bottom: 20rpx solid #fff;
    }

    .swiper {
      .swiper-item {
        height: 100%;
        margin-left: 24rpx;
        display: flex;
        flex-direction: column;

        .item-top {
          display: flex;
          align-items: center;
          justify-content: center;
          padding-bottom: 56rpx;

          .item-top-text {
            margin: 0 8rpx;
            font-size: 28rpx;
            color: #595757;
          }

          .item-top-images {
            position: relative;
            height: 48rpx;
            display: flex;
          }

          .item-top-img {
            width: 48rpx;
            height: 48rpx;
            border: 1rpx solid #fff;
            border-radius: 50%;
            background: #eee;
            // 设置定位，使其可以重叠
            position: relative;
            z-index: 1;

            &:not(:first-child) {
              margin-left: -24rpx; // 设置负边距使图片重叠
            }

            // 让序号大的图片z-index更小，确保正确的遮挡顺序
            @for $i from 1 through 5 {
              &:nth-child(#{$i}) {
                z-index: 6 - $i;
              }
            }
          }

          .item-top-total {
            font-size: 28rpx;
            color: #595757;
            margin-left: 8rpx;
          }
        }

        .content-scroller {
          padding-bottom: 32rpx;
          flex: 1;
          overflow: auto;
        }
        .item-content {
          flex: 1;
          overflow: hidden;
          padding: 0 32rpx;
          // margin-bottom: 56rpx;
          position: relative;
          border-radius: 20rpx 20rpx 0 0;
          border: 2rpx solid #25C959;
          background: #F6F8FA;
          border-bottom: none;

          .item-stage {
            padding-top: 32rpx;
            height: 100%;
            display: flex;
            flex-direction: column;
          }

          &::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 300rpx;
            background: linear-gradient( 180deg, #CBFFC7 0%, #F6F8FA 100%);
            border-radius: 20rpx 20rpx 0 0;
          }

          .item-title {
            position: relative;
            z-index: 1;

            .item-title-index {
              position: relative;

              .index-num {
                position: relative;
                display: inline-block;
                width: 58rpx;
                padding-bottom: 6rpx;
                font-size: 48rpx;
                text-align: center;
                line-height: 60rpx;
                color: #303030;
                font-weight: bold;
                z-index: 1;
              }

              .index-img {
                position: absolute;
                bottom: 2rpx;
                left: -12rpx;
                width: 82rpx;
                height: 26rpx;
              }
            }

            .item-content-text {
              padding: 17rpx 0 0 20rpx;
              font-size: 32rpx;
              line-height: 48rpx;
              color: #303030;
              font-weight: bold;
            }
          }

          .item-desc {
            position: relative;
            z-index: 1;
            display: block;
            padding: 32rpx 0 56rpx 0;
            font-size: 24rpx;
            line-height: 36rpx;
            color: #303030;
            border-bottom: 2rpx dashed #E6D6FF;
          }

          .item-image {
            position: relative;
            width: 582rpx;
            height: 380rpx;
            padding: 26rpx 0;
            z-index: 2;
            border-bottom: 2rpx dashed #E6D6FF;

            .item-image-img {
              width: 582rpx;
              height: 328rpx;
              border-radius: 16rpx;
            }

            .item-image-label {
              position: absolute;
              top: 26rpx;
              right: 0;

              padding: 0 24rpx;
              font-size: 28rpx;
              line-height: 50rpx;
              color: #fff;
              background: rgba(0,0,0,0.6);
              border-radius: 0 16rpx 0 0;
            }
          }

          .item-subtitle {
            display: block;
            padding-top: 24rpx;
            font-weight: 500;
            font-size: 32rpx;
            color: #303030;
            line-height: 72rpx;
            z-index: 1;
          }

          .item-course {
            display: flex;
            flex-direction: column;
            width: 100%;
            padding: 32rpx;
            margin-top: 32rpx;
            background: #FFFFFF;
            border-radius: 20rpx;

            .course-title {
              display: flex;
              align-items: center;

              .course-title-label {
                display: flex;
                height: 36rpx;
                padding: 0 16rpx;
                background: #13A86C;
                border-radius: 4rpx;
                transform: skewX(-15deg);

                .label-text {
                  font-weight: 500;
                  font-size: 24rpx;
                  color: #FFFFFF;
                  line-height: 36rpx;
                  transform: skewX(15deg);
                }
              }

              .course-title-label-0 {
                background: #A83EBF;
              }

              .course-title-text {
                padding-left: 16rpx;
                font-weight: 500;
                font-size: 28rpx;
                color: #1C234C;
                line-height: 42rpx;
              }
            }

            .course-info {
              padding: 32rpx 0 20rpx 0;
              font-size: 24rpx;
              color: #303030;
              line-height: 36rpx;
            }

            .course-btn {
              display: flex;
              align-items: center;
              justify-content: space-between;
              height: 68rpx;
              padding-top: 20rpx;
              border-top: 2rpx dashed #E6D6FF;

              .btn-left {
                display: flex;
                align-items: center;

                .btn-item {
                  padding-right: 40rpx;
                  font-size: 28rpx;
                  color: #7151ED;
                  line-height: 48rpx;
                }
              }

              .btn-right {
                display: flex;
                align-items: center;
                justify-content: center;
                width: 40rpx;
                height: 40rpx;
                border-radius: 50%;
                background: #7151ED;
              }
            }
          }
        }

        .content-2 {
          border: 2rpx solid #50B1F5;

          &::after {
            background: linear-gradient( 180deg, #ADDFFF 0%, #F6F8FA 100%);
          }
        }

        .content-3 {
          border: 2rpx solid #FF8624;

          &::after {
            background: linear-gradient( 180deg, #FFD2AD 0%, #F6F8FA 100%);
          }
        }

        .content-4 {
          border: 2rpx solid #7151ED;

          &::after {
            background: linear-gradient( 180deg, #EED5FF 0%, #F6F8FA 100%);
          }
        }

        .content-5 {
          border: 2rpx solid #EF5488;

          &::after {
            background: linear-gradient( 180deg, #FFD5EA 0%, #F6F8FA 100%);
          }
        }
      }
    }
  }
}

swiper {
  height: 100%;

  swiper-item {
    display: flex;
    flex-direction: column;
  }
}
</style>

<style lang="scss">
:deep(.uicon-arrow-right) {
  color: #fff !important;
}
</style>
